<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            蓝牙开锁
        </div>
    </header>
    <div class="aui-content aui-margin-b-15" style="margin-top:50px;">
        </br>

        <div style="background-color:white; height: 100%;width: 100%;margin-top:2%;margin-bottom:100px;">
            <table class="table" style='width:100%;height: 200px' id="table">
                <thead>
                    <tr
                        style="text-align: center;background-color: #DCE9F2;color: #467aa7;font-size: 12px;font-weight: bold;">
                        <td style='display:none;' algin='center'></td>
                        <td style="display:none;" algin='center'>UUID</td>
                        <td style="display:none;" algin='center'>properties</td>
                        <!-- <td algin='center'>permissions</td> -->
                        <td style="display:none;" algin='center'>serviceUUID</td>
                        <!-- <td algin='center' style="display:none;">manufacturerData</td> -->
                        <td algin='center'>蓝牙开锁</td>
                        <td style="display:none;">id</td>
                    </tr>
                </thead>
                <tbody id="tbodyHtml">
                </tbody>
            </table>
        </div>
    </div>


    <footer class="aui-bar aui-bar-tab" id="footer">
        <div class="aui-btn aui-btn-info aui-btn-block"
            style="width:60%;margin-left:20%;font-size: 12px;font-weight: bold;" onclick="disConnectBlue()">断开蓝牙
        </div>
    </footer>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript">
    //光标所在id
    // var idSelector = "";
    var uuid = "";
    //初始化查询仓库下拉框
    apiready = function () {
        uuid = api.pageParam.uuid;

        init(uuid);
    }
    function init(uuid) {

        //console.log(uuid);
        var ble = api.require('ble');
        ble.initManager({ single: true }, function (ret) {
            if (ret.state == "poweredOn") {
               
                api.showProgress({
                    title: '蓝牙连接中...'
                });
                
                ble.scan({
                    
                }, function (ret) {
                    if (ret.status) {

                        ble.getPeripheral(function (ret) {
                            if (ret) {
                                var data = JSON.stringify(ret);
                                var myobj = eval("(" + data + ")");
                                var list = myobj.peripherals;
                                ble.connect({
                                    peripheralUUID: uuid
                                }, function (ret, err) {
                                    if (ret.status) {
                                        api.hideProgress();
                                        alert("连接成功！");
                                        ble.discoverService({
                                            peripheralUUID: uuid
                                        }, function (ret) {
                                            if (ret) {

                                                let services = ret.services;
                                                //console.log(services);
                                                var html = "";
                                                for (let item of services) {
                                                    ble.discoverCharacteristics({
                                                        serviceUUID: item,
                                                        peripheralUUID: uuid
                                                    }, function (ret) {
                                                        if (ret) {

                                                            for (let _obj of ret.characteristics) {
                                                                if (_obj.properties == "18") {
                                                                  //  console.log("_obj.uuid" + _obj.serviceUUID);
                                                                  //  console.log("_obj.uuid" + _obj.uuid);
                                                                    ble.setNotify({
                                                                        peripheralUUID: uuid,
                                                                        serviceUUID: _obj.serviceUUID,
                                                                        characteristicUUID: _obj.uuid,
                                                                    }, function (res, err) {
                                                                        if (res) {
                                                                            console.log(JSON.stringify(res))
                                                                        } else {
                                                                            console.log(JSON.stringify(res))
                                                                        }
                                                                    });
                                                                }
                                                            }

                                                            var data = JSON.stringify(ret);
                                                            var myobj = eval("(" + data + ")");
                                                            var list = myobj.characteristics;
                                                            for (var i = 0; i < list.length; i++) {
                                                                if(list[i].properties != "write"){
                                                                    continue;
                                                                }
                                                                html += "<tr style='text-align: center;background-color: #F5F5F5;color: black;font-size: 12px;height :15px'>";
                                                                html += "<td style='display:none;'><input name='sub' type='checkbox' /></td>";
                                                                html += "<td style='display:none;' name='vin' >" + list[i].uuid + "</td>";
                                                                html += "<td style='display:none;' name='carno' >" + list[i].properties + "</td>";
                                                                // html += "<td name='carno' >" + list[i].permissions + "</td>";
                                                                html += "<td style='display:none;' name='seq' >" + list[i].serviceUUID + "</td>";
                                                                html += "<td name='sub_mrlcode' ><button  onclick = 'unlock(\"" + list[i].uuid + "\",\"" + list[i].serviceUUID + "\")'>蓝牙开锁</button></td>";
                                                                html += "</tr>";
                                                            }
                                                            $api.html($api.byId("tbodyHtml"), html);

                                                        }
                                                    });


                                                }
                                                //===========
                                            }
                                        });

                                    } else {
                                        api.hideProgress();
                                        // alert(err.code);
                                    }
                                });



                            }
                        });

                    }
                });
                // , 3000)
            }
        });

    }


    function unlock(characteristics, serviceUUID) {
        var ble = api.require('ble');
        // console.log("uuid    " + uuid.replace(new RegExp(":", "gm"), ""));
        // console.log("v   " + serviceUUID);
        // console.log("characteristics       " + characteristics);
        // 获取当前时间
        var currentTime = new Date();

        // 将当前时间转换为十六进制表示
        var year = zeroPadding1(parseInt(currentTime.getFullYear().toString().slice(-2)).toString(16), 2);
        var month = zeroPadding1((currentTime.getMonth() + 1).toString(16), 2);
        var dat = zeroPadding1(currentTime.getDate().toString(16), 2);
        var hour = zeroPadding1(currentTime.getHours().toString(16), 2);
        var min = zeroPadding1(currentTime.getMinutes().toString(16), 2);
        var sec = zeroPadding1(currentTime.getSeconds().toString(16), 2);

        var hexTime = year + month + dat + hour + min + sec;
        // console.log(parseInt((currentTime.getFullYear().toString().slice(-2)).toString(16)));
        // console.log(currentTime);
        //console.log(hexTime);
        var val = '0100000d' + uuid.replace(new RegExp(":", "gm"), "") + hexTime;
        //console.log(val);
        var valuedesc = calculateHexSum(val);
        //var  value = valuedesc.toString(16)
        var value = backOneByte(valuedesc.toString(16));
        //console.log(value);        
        val = '0100000d' + uuid.replace(new RegExp(":", "gm"), "") + hexTime + value;
        //console.log(val);
        ble.writeValueForCharacteristic({
            peripheralUUID: uuid,
            serviceUUID: serviceUUID,
            characteristicUUID: characteristics,
            writeType: 'response',
            value: val
        }, function (ret) {
            if (ret) {
                // api.alert({ msg: JSON.stringify(ret) });
                //蓝牙锁指令
                var valbluetooth = 'E000000D' + uuid.replace(new RegExp(":", "gm"), "") + hexTime;
                //console.log(valbluetooth);
                var valuedescbluetoot = calculateHexSum(valbluetooth);
                //var  value = valuedesc.toString(16)
                var valuebluetooth = backOneByte(valuedescbluetoot.toString(16));
                 //console.log(valuebluetooth);
                var unlock = uuid.replace(new RegExp(":", "gm"), "") + hexTime + valuebluetooth;
                //console.log(unlock);
                var serverUrl = localStorage.getItem('serverUrl');
                var url = serverUrl + "/app/encryptCode";
                var un = localStorage.getItem('un');

                var params = new Object();
                params.url = url;
                params.method = 'post';
                params.dataType = 'json';
                var data = {
                    values: {
                        un: un,
                        unlock: unlock,
                        uuid:uuid
                    }
                };
                api.ajax({
                    url: url,
                    method: 'post',
                    dataType: 'json',
                    timeout: 300,
                    returnAll: false,
                    data: data
                }, function (ret, err) {

                    var data = JSON.stringify(ret);
                    var myobj = eval("(" + data + ")");
                    //成功
                    if (myobj.code == '0') {

                        var encryCode = 'E000000D' + myobj.encryCode
                        //console.log(encryCode);
                        ble.writeValueForCharacteristic({
                            peripheralUUID: uuid,
                            serviceUUID: serviceUUID,
                            characteristicUUID: characteristics,
                            writeType: 'response',
                            value: encryCode
                        }, function (ret) {
                            if (ret) {
                            }
                        });
                    } else {
                        api.toast({
                            msg: myobj.message,
                            duration: 3000
                        });
                    }


                });

            }
        });







        // disConnectBlue();
    }

    function backOneByte(value) {
        if (value.length >= 4) {
            //console.log(value);
            value = value.substring(value.length - 4, value.length);
            var firstCase = value.substring(0, 1);
            if (firstCase == "0") {
                value = value.substring(value.length - 2, value.length);
            }
            //console.log(value);
        } else if (value.length == 3) {
            //console.log(value);
            value = value.substring(value.length - 2, value.length);
            //console.log(value);
        } else if (value.length == 2) {

        } else if (value.length == 1) {
            value = "0" + value;
        }
        return value;
    }

    function calculateHexSum(str) {
        let sum = 0;
        for (let i = 0; i < str.length; i += 2) {
            const hex = parseInt(str.substr(i, 2), 16);
            sum += hex;
        }
        return sum;
    }

    function zeroPadding1(num, length) {
        var len = num.toString().length;
        while (len < length) {
            num = "0" + num;
            len++;
        }
        return num;
    }

    function disConnectBlue() {
        var ble = api.require('ble');

        ble.disconnect({
            peripheralUUID: uuid
        }, function (ret, err) {
            if (ret.status) {
                alert("断开连接成功！");
            }
        });
        // ble.clean();
    }

    //返回按钮
    function closeWin() {

        api.closeWin({});
    }


    function doscan(uuid) {
        var ble = api.require('ble');
        ble.discoverService({
            peripheralUUID: uuid
        }, function (ret) {
            if (ret) {

                let services = ret.services;
                console.log(services);
                var html = "";
                for (let item of services) {
                    ble.discoverCharacteristics({

                        serviceUUID: item,
                        peripheralUUID: uuid

                    }, function (ret) {
                        if (ret) {

                            for (let _obj of ret.characteristics) {
                                if (_obj.properties == "18") {
                                    console.log("_obj.uuid" + _obj.serviceUUID);
                                    console.log("_obj.uuid" + _obj.uuid);
                                    ble.setNotify({
                                        peripheralUUID: uuid,
                                        serviceUUID: _obj.serviceUUID,
                                        characteristicUUID: _obj.uuid,
                                    }, function (des) {
                                        if (des) {
                                            // alert(111);
                                            // api.alert({ msg: JSON.stringify(des) });
                                        } else {
                                            // api.alert({ msg: JSON.stringify(des) });
                                        }
                                    });
                                }
                            }

                            // api.alert({ msg: JSON.stringify(ret) });
                            // console.log(JSON.stringify(ret));
                            // for (let _obj of ret.characteristics) {

                            var data = JSON.stringify(ret);
                            var myobj = eval("(" + data + ")");
                            //var list1 = JSON.stringify(ret).peripherals;
                            var list = myobj.characteristics;
                            // $api.html($api.byId("tbodyHtml"), html);
                            //===============
                            //遍历
                            for (var i = 0; i < list.length; i++) {

                                html += "<tr style='text-align: center;background-color: #F5F5F5;color: black;font-size: 12px;height :15px'>";

                                html += "<td ><input name='sub' type='checkbox' /></td>";
                                html += "<td name='vin' >" + list[i].uuid + "</td>";
                                html += "<td name='carno' >" + list[i].properties + "</td>";
                                html += "<td name='carno' >" + list[i].permissions + "</td>";
                                html += "<td name='seq' >" + list[i].serviceUUID + "</td>";

                                html += "<td name='sub_mrlcode' ><button  onclick = 'unlock(\"" + list[i].uuid + "\",\"" + list[i].serviceUUID + "\")'>蓝牙开锁</button></td>";


                                html += "</tr>";
                            }

                            $api.html($api.byId("tbodyHtml"), html);

                        }
                    });

                }
                //===========
            }
        });
    }
</script>

</html>